package com.company.cloud.club.modules.service.impl;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.company.cloud.club.modules.core.dto.project.CaseDto;
import com.company.cloud.club.modules.core.util.ValidateUtil;
import com.company.cloud.club.modules.db.dao.BannerMapper;
import com.company.cloud.club.modules.db.dao.ProjectCaseMapper;
import com.company.cloud.club.modules.db.dao.ProjectMapper;
import com.company.cloud.club.modules.db.domain.Banner;
import com.company.cloud.club.modules.db.domain.Project;
import com.company.cloud.club.modules.db.domain.UserInfo;
import com.company.cloud.club.modules.dto.product.OrderParam;
import com.company.cloud.club.modules.dto.product.OrderParamDto;
import com.company.cloud.club.modules.dto.project.ProjectDto;
import com.company.cloud.club.modules.dto.project.PageListDto;
import com.company.cloud.club.modules.dto.project.UserInvitationSaveParam;
import com.company.cloud.club.modules.service.ProjectService;
import com.company.cloud.club.modules.service.UserInfoService;
import com.company.cloud.club.modules.utils.JWTUtil;
import com.company.cloud.club.modules.utils.LoginContextUtils;
import com.company.cloud.common.asserts.ValidatorUtils;
import com.company.cloud.common.bean.LoginSimpleUserInfo;
import com.company.cloud.common.exception.BusinessException;
import com.company.cloud.common.utils.CheckUtils;
import com.company.cloud.common.utils.HttpContextUtils;
import com.company.cloud.common.utils.PasswordUtils;
import com.company.cloud.common.utils.StrSplitUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
public class ProjectServiceImpl extends ServiceImpl<ProjectMapper, Project> implements ProjectService {

    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private BannerMapper bannerMapper;


    @Autowired
    private ProjectMapper projectMapper;

    @Autowired
    private ProjectCaseMapper projectCaseMapper;

    @Override
    public boolean submit(Project project) {
        int flag = baseMapper.insert(project);
        return flag == 1;
    }

    @Override
    public Project getOne(String id) {
        return baseMapper.selectById(id);
    }

    @Override
    public PageListDto listPage(ProjectDto projectDto) {
        List<Project> list = projectCaseMapper.listPage(projectDto.getCurrentPage(), projectDto.getPageSize());
        int count = projectCaseMapper.proCount();
        return PageListDto.from(projectDto, count, list.toArray());

    }

    @Override
    public PageListDto casePage(ProjectDto projectDto) {
        return null;
    }

    @Override
    public List<Banner> bannerList() {
        return bannerMapper.bannerList();
    }

    @Override
    public List<CaseDto> caseList() {
        return projectCaseMapper.caseList();
    }

    @Override
    public String tokenGain(String uid) {
        if(!Objects.equals(uid,"a529605da0abe9d05d63e032f557a25b")){
            throw new RuntimeException("验证不通过,验证失败！！！");
        }
        final String token = JWTUtil.createToken(uid, 120 * 60 * 1000);
        //此处id写死用户id,如更改请修改数据   作用 ： 门票系统保存token
   /*     final CustUserInfo custUserInfo = projectCaseMapper.CustUser(2082);
        if(ValidateUtil.isValid(custUserInfo)){
            final Integer id = custUserInfo.getId();
            projectCaseMapper.CustUserUpdate(id,token);
        }*/
        return token;
    }

    @Override
    public void ticketSave(UserInvitationSaveParam params) {
        params.setSourceOne("2");
        params.setCompanyNo("PTC");
        ValidatorUtils.validate(params);
        if(params.getType()==1){
            this._registerByUserName2Mobile(params);//添加
        } else {
            this._registerByUserName2MobileSave(params);//修改
        }
    }

    @Override
    public void OrderSave(OrderParam param) {
        OrderParamDto params=new OrderParamDto();
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        params.setOrderNo(param.getOrderNo());
        params.setOrderDate(LocalDateTime.parse(param.getOrderDate(),df));
        params.setFund(new BigDecimal(param.getFund()));
        params.setProductFund(new BigDecimal(param.getFund()));
        params.setStatus(param.getStatus());
        params.setOrderParam( JSON.toJSONString(param.getOrderParam()));
        params.setUserId("114");
        projectCaseMapper.orderInster(params);
    }

    private UserInfo _registerByUserName2MobileSave(UserInvitationSaveParam params) {

        ValidatorUtils.validate(params);
        params.setRegIp(HttpContextUtils.getClientIP());
        params.setRegWay("4");
        validate(params);
        check_onlySave(params);
        UserInfo user = register(params);
        return user;
    }

    private UserInfo _registerByUserName2Mobile(UserInvitationSaveParam params) {

        ValidatorUtils.validate(params);
        params.setRegIp(HttpContextUtils.getClientIP());
        params.setRegWay("4");
        validate(params);
        check_only(params);
        UserInfo user = register(params);
        return user;
    }

    private void validate(UserInvitationSaveParam param) {
        ValidatorUtils.validate(param);
    }

    private void check_onlySave(UserInvitationSaveParam param) {
        if ("4".equals(param.getRegWay())) { //手机
            if (StringUtils.isEmpty(param.getMobile())) {
                throw new RuntimeException("手机号不能为空");
            }
            //验证手机号唯一
            List<UserInfo> list = userInfoService.list(new QueryWrapper<UserInfo>()
                    .eq("mobile", param.getMobile())
            );
            if (list.size() > 0) {
                list.forEach(m -> {
                    param.setUserId(String.valueOf(m.getId()));
                });
            } else {
                param.setType(1);
                param.setUserName(param.getMobile());
            }

        }
    }

    /***/
    private void check_only(UserInvitationSaveParam param) {
        if ("4".equals(param.getRegWay())) { //手机
            if (StringUtils.isEmpty(param.getMobile())) {
                throw new RuntimeException("手机号不能为空");
            }
            //验证手机号唯一
            int count = userInfoService.count(new QueryWrapper<UserInfo>()
                    .eq("mobile", param.getMobile())
            );
            if (count > 0) {
                throw new RuntimeException("手机号已存在");
            }
            param.setUserName(param.getMobile());
        }
        if ("4".equals(param.getRegWay())) { //用户名
            if (StringUtils.isEmpty(param.getUserName())) {
                throw new RuntimeException("用户名不能为空");
            }
            //验证用户名唯一 用户名全系统唯一
            int count = userInfoService.count(new QueryWrapper<UserInfo>()
                    .eq("user_name", param.getUserName()));
            if (count > 0) {
                throw new BusinessException("用户名已存在");
            }
        }
        if ("4".equals(param.getRegWay())) { //用户名和手机号
            if (StringUtils.isEmpty(param.getUserName())) {
                throw new BusinessException("用户名不能为空");
            }
            if (StringUtils.isEmpty(param.getMobile())) {
                throw new BusinessException("手机号不能为空");
            }
            //验证用户名唯一 用户名全系统唯一
            int count = userInfoService.count(new QueryWrapper<UserInfo>()
                    .eq("user_name", param.getUserName()));
            if (count > 0) {
                throw new BusinessException("用户名已存在");
            }
            //验证手机号唯一
            int count2 = userInfoService.count(new QueryWrapper<UserInfo>()
                    .eq("mobile", param.getMobile())
            );
            if (count2 > 0) {
                throw new BusinessException("手机号已存在");
            }
        }

    }

    @Transactional
    public UserInfo register(UserInvitationSaveParam param) {
        UserInfo userInfo = new UserInfo();
        if (ValidateUtil.isValid(param.getUserId())) {
            userInfo.setId(Integer.valueOf(param.getUserId()));
        }
        userInfo.setCompanyNo(param.getCompanyNo());
        userInfo.setUserTypeOne(param.getUserTypeOne());
        userInfo.setUserTypeTwo(param.getUserTypeTwo());
        userInfo.setSourceOne(param.getSourceOne());
        userInfo.setSourceTwo(param.getSourceTwo());
        userInfo.setUserName(param.getUserName());
        userInfo.setNickName(param.getNickName());
        userInfo.setUserState("1");
        userInfo.setNationCode(param.getNationCode());
        userInfo.setMobile(param.getMobile());
        userInfo.setEmail(param.getEmail());
        userInfo.setHeadImg(param.getHeadImg());
        if (!StringUtils.isEmpty(param.getPassword())) {
            String[] passwords = PasswordUtils.getMd5Password(param.getPassword());
            userInfo.setPassword(passwords[0]);
            userInfo.setSalt(passwords[1]);
        }
        userInfo.setShareCode(IdUtil.getSnowflake(2, 2).nextIdStr());
        userInfo.setRegTime(LocalDateTime.now());
        userInfo.setRegIp(param.getRegIp());
        userInfo.setRegClientType(param.getClientType());
        userInfo.setRegDeviceNo(param.getClientDeviceNo());
        userInfo.setLlType(param.getLlType());
        userInfo.setLongitude(param.getLongitude());
        userInfo.setLatitude(param.getLatitude());
        userInfo.setUserTags(StrSplitUtils.list2string(param.getUserTags()));
        userInfo.setCdt(LocalDateTime.now());
        userInfo.setCip("0:0:0:0:0:0:0:1");
        userInfo.setCman(userInfo.getUserName());
        //员工
        userInfo.setTel(param.getTel());
        userInfo.setQq(param.getQq());
        userInfo.setDeptId(param.getDeptId());
        userInfo.setIsDeptManager(param.getIsDeptManager());
        userInfo.setDataAuthorityType(param.getDataAuthorityType());
        userInfo.setDataAuthorityScope(StrSplitUtils.list2string(param.getDataAuthorityScope()));
        userInfo.setJobCode(StrSplitUtils.list2string(param.getJobCode()));
        userInfo.setIsManager(param.getIsManager());
        userInfo.setCustType(param.getCustType());
        userInfo.setCustCode(param.getCustCode());
        userInfo.setCustName(param.getCustName());
        userInfo.setIdentity(param.getIdentity());
        userInfo.setRegTime(LocalDateTime.now());
        if (param.getRegTime() != null) {
            //SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            //  String cTime_2 = formatter.format(param.getRegTime());
            userInfo.setRegTime(LocalDateTime.parse(param.getRegTime(), df));
        }

        userInfo.setIdentityType(param.getIdentityType());
        if (Objects.equals(1, param.getType())) {
            userInfoService.save(userInfo);
        }
        if (Objects.equals(2, param.getType())) {
            userInfoService.updateById(userInfo);
        }
        return userInfo;
    }


}
